package test.httpClient;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpClientJDK {
	
	public static void main(String[] args) {
		String urlStr = "http://localhost:8080/httpServer/servlet/SP_HTTP_H2D_InvalidBarcode?name=你";
		doGet(urlStr);
	}
	
	
	
	public static void doGet(String urlStr) {
        try {
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setDoOutput(true); // 设置该连接是可以输出的
            connection.setRequestMethod("GET"); // 设置请求方式
//            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            String line = null;
            StringBuilder result = new StringBuilder();
            while ((line = br.readLine()) != null) { // 读取数据
                result.append(line + "\n");
            }
            connection.disconnect();

            System.out.println(result.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	
	public static void doPostKV(String urlStr) {
		 try {
	            URL url = new URL(urlStr);
	            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

	            connection.setDoInput(true); // 设置可输入
	            connection.setDoOutput(true); // 设置该连接是可以输出的
	            connection.setRequestMethod("POST"); // 设置请求方式
	            connection.setRequestProperty("content-type", "application/x-www-form-urlencoded; charset=UTF-8");

	            PrintWriter pw = new PrintWriter(new BufferedOutputStream(connection.getOutputStream()));
	            pw.write("code=001&name=测试");
	            pw.flush();
	            pw.close();

	            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
	            String line = null;
	            StringBuilder result = new StringBuilder();
	            while ((line = br.readLine()) != null) { // 读取数据
	                result.append(line + "\n");
	            }
	            connection.disconnect();

	            System.out.println(result.toString());
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	}
}
